<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    cancelText="关闭"
    @cancel="onButtonCancelClick"
    :showOkBtn="false"
    width="880px"
  >
    <BasicTable
      @register="registerUsersTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
      :data-source="ProjectUsersData.users"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddUsers"> 新增 </a-button>
        <a-button type="error" @click="deleteUsers"> 删除 </a-button>
      </template>
    </BasicTable>
    <setProjectUsers @register="registerPlatformUserList" @success="successReload" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref, inject, provide } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { getProjectUsers, deleteProjectUsers } from '/@/api/project/project';
  import { userTableColumns } from './project.data';

  //引入子组件
  import setProjectUsers from './SetProjectUsers.vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { BasicTable, useTable } from '/@/components/Table';

  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';

  const { createMessage } = useMessage();

  const [registerPlatformUserList, { openModal: openUsersList }] = useModal();

  export default defineComponent({
    name: 'ProjectUsersMenagement',
    components: {
      BasicModal,
      BasicTable,
      setProjectUsers,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //定义模块的名称，提供给子孙组件获取使用
      const UsersModuleName = ref('项目人员管理');
      provide('UsersModuleName', UsersModuleName);

      const op = ref(OperationTypeEnum.UN_KNOWN);
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');
      const moduleName = inject<string>('moduleName');
      const tableTitle = ref('项目已有人员');

      const dataId = ref('');

      //勾选的用户id集合
      const uids = ref<number[] | string[]>([]);

      //处理过后的table数据
      const ProjectUsersData = reactive({
        users: [],
      });

      const [registerUsersTable, { reload, getSelectRowKeys, clearSelectedRowKeys }] = useTable({
        title: tableTitle,
        // api: getProjectUsers,
        columns: userTableColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        bordered: true,
        showIndexColumn: true,
        pagination: true, //关闭分页
        rowSelection: { type: 'checkbox' },
        rowKey: 'id',
        clickToRowSelect: false,
      });

      /**
       * 接收父组件传递的数据并处理
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //接收父组件传递的数据
        console.log(data);
        //判断是否传入op属性
        if (data?.op) {
          op.value = data.op;
        }

        if (data?.dataId) {
          dataId.value = data.dataId;
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        setModalProps({ confirmLoading: false });

        geProjectUsers();
      });

      /**
       * 获取指定项目编码的人员列表
       */
      async function geProjectUsers() {
        //更新数据前先清空原来的数据，否则页面不刷新显示最新数据
        if (ProjectUsersData.users.length > 0) {
          ProjectUsersData.users = [];
        }
        //调用后端接口获取数据
        getProjectUsers(dataId.value)
          .then((res) => {
            console.log('res', res);
            if (res != null) {
              //处理返回数据
              res.forEach((user) => {
                let result = {
                  id: user.id,
                  name: user.name,
                  phone: user.phone,
                };
                ProjectUsersData.users.push(result);
              });
              console.log('ProjectUsersData', ProjectUsersData);
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 打开新增项目人员窗口
       */
      function onAddUsers() {
        openUsersList(true, { op: '新增项目人员', dataId: dataId.value });
      }

      /**
       * 删除项目人员
       */
      function deleteUsers() {
        //获取设置选中的用户id集合
        uids.value = getSelectRowKeys();
        if (uids.value.length == 0) {
          createMessage.warning('请选择要删除的项目人员', 2);
        } else {
          deleteProjectUsers({ project: dataId.value, uids: uids.value })
            .then((res) => {
              console.log('res', res);
              //res判断结果：同时==undefined和null
              if (res == undefined && (res == null || Object.keys(res).length == 0)) {
                createMessage.success('删除成功。', 2);
                successReload();
              }
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        }
      }

      /**
       * 点击关闭按钮
       */
      async function onButtonCancelClick() {
        closeModal();
        emit('success');
        //清空选中的行
        clearSelectedRowKeys();
      }

      /**
       * 确认操作之后刷新页面
       */
      function successReload() {
        geProjectUsers();
        reload();
      }

      return {
        op,
        moduleName,
        modalTitle,
        UsersModuleName,
        registerModal,
        registerUsersTable,
        geProjectUsers,

        registerPlatformUserList,

        successReload,
        onAddUsers,
        deleteUsers,

        ProjectUsersData,
        onButtonCancelClick,
      };
    },
  });
</script>
